package com.js.service.bot.response;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.js.common.annotation.ResponseClass;
import com.js.common.annotation.ResponseCommand;
import com.js.common.core.BotHandler;
import com.js.service.bot.core.StorageService;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@EnableScheduling
@Scope("prototype")
@ResponseClass("米游社")
public class MysService extends BotHandler {

    @Resource
    private StorageService storageService;
    //请求地址
    private String hostRecord = "https://api-takumi-record.mihoyo.com/";
    //角色详情
    private String character = "game_record/app/genshin/api/character";
    //版本号 切勿乱修改
    private String APP_VERSION = "2.40.0";
    //米游社原神签到官方ID 切勿乱修改
    private String ACT_ID = "e202009291139501";
    //米游社签到校验码
    private String salt = "dWCcD2FsOUXEstC5f9xubswZxEeoBOTc";
    //代理设备
    private String USER_AGENT = String.format("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/%s", APP_VERSION);
    //Referer请求头来源地址
    private String REFERER_URL = String.format("https://webstatic.mihoyo.com/bbs/event/signin-ys/index.html?bbs_auth_required=%s&act_id=%s&utm_source=%s&utm_medium=%s&utm_campaign=%s", true, ACT_ID, "bbs", "mys", "icon");

    @ResponseCommand(
            value = "mys",
            name = "绑定米游社cookie"
    )
    public MessageChain bind(Long userId, Long targetId, String command, MessageChain messageChain) {
        setCache("bindCookie", null);
        MessageChainBuilder result = new MessageChainBuilder();
        result.append("请发送cookie，或发送指令[exit]退出");
        return result.build();
    }

    public MessageChain bindCookie(Long userId, Long targetId, String command, MessageChain messageChain) {
        String cookie = messageChain.contentToString();
        storageService.addStorage(userId, "mys_cookie", cookie);
        MessageChainBuilder result = new MessageChainBuilder();
        result.append("绑定成功");
        return result.build();
    }

    @ResponseCommand(
            value = "(.+)信息",
            name = "角色信息",
            reg = "信息"
    )
    public MessageChain character(Long userId, Long targetId, String command, MessageChain messageChain) {
        String uid = getContent().get(0);
        String server = getServer(uid);
        if(StrUtil.isEmpty(server)){
            MessageChainBuilder result = new MessageChainBuilder();
            result.append("UID错误");
            return result.build();
        }
        String cookie = storageService.getStorageValue(userId, "mys_cookie");
        if(StrUtil.isEmpty(cookie)){
            cookie = storageService.getStorageValue(getMaster(), "mys_cookie");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("role_id", uid);
        param.put("server", server);
        String body = JSONUtil.toJsonStr(param);
        String res = HttpUtil.createPost(hostRecord + character)
                .headerMap(getHeaders(body, cookie), true)
                .body(body)
                .execute()
                .body();

        MessageChainBuilder result = new MessageChainBuilder();
        result.append(res);
        return result.build();
    }

    public String getServer(String uid){
        String server = "";
        switch (uid.charAt(0)){
            case '1':
            case '2':
                server = "cn_gf01";
                break;
            case '5':
                server = "cn_qd01";
                break;
        }
        return server;
    }

    /**
     * 重写接口请求头getHeaders方法
     *
     * @return Header[]
     */
    public Map<String, String> getHeaders(String body, String cookie) {
        Map<String, String> header = new HashMap<>();
        /*header.put("x-rpc-device_id", UUID.randomUUID().toString().replace("-", "").toUpperCase());
        header.put("Content-Type", "application/json;charset=UTF-8");
        header.put("DS", getDS());
        header.put("Cookie", cookie);
        header.put("User-Agent", USER_AGENT);
        header.put("Referer", REFERER_URL);
        header.put("Accept-Encoding", "gzip, deflate, br");
        header.put("x-rpc-channel", "appstore");
        header.put("accept-language", "zh-CN,zh;q=0.9,ja-JP;q=0.8,ja;q=0.7,en-US;q=0.6,en;q=0.5");
        header.put("accept-encoding", "gzip, deflate");
        header.put("x-requested-with", "com.mihoyo.hyperion");
        header.put("Host", "api-takumi.mihoyo.com");*/
        String appVersion = storageService.getStorageValue(getMaster(), "app_version");
        header.put("app_version", appVersion);
        header.put("x-rpc-client_type", "5");
        header.put("Referer", "https://webstatic.mihoyo.com");
        header.put("User-Agent", USER_AGENT);
        header.put("DS", getDS(body));
        header.put("Cookie", cookie);
        return header;
    }

    /**
     * 原神签到DS算法
     *
     * @return String
     */
    public String getDS(String body) {
        String n = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs";
        String t = (System.currentTimeMillis() / 1000) + "";
        String r = getRandomStr();
        String ds = DigestUtil.md5Hex("salt=" + n + "&t=" + t + "&r=" + r + "&b=" + body + "&q=");
        return String.format("%s,%s,%s", t, r, ds);
    }

    /**
     * 获取随机字符串用于DS算法中
     *
     * @return String
     */
    public String getRandomStr() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 6; i++) {
            String CONSTANTS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int number = random.nextInt(CONSTANTS.length());
            char charAt = CONSTANTS.charAt(number);
            sb.append(charAt);
        }
        return sb.toString();
    }

    @PostConstruct
    public void initAppVersion() {
        String appVersion = storageService.getStorageValue(getMaster(), "app_version");
        if(StrUtil.isEmpty(appVersion)){
            storageService.addStorage(getMaster(), "app_version", "2.40.0");
        }
    }

    public static void main(String[] args) {
        System.out.println("Yz-" + DigestUtil.md5Hex("501407504").substring(0, 5));
        String n = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs";
        int t = Math.round(new Date().getTime() / 1000);

        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 6; i++) {
            String CONSTANTS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int number = random.nextInt(CONSTANTS.length());
            char charAt = CONSTANTS.charAt(number);
            sb.append(charAt);
        }

        String r = sb.toString();
        Map<String, Object> param = new HashMap<>();
        param.put("role_id", "501407504");
        param.put("server", "cn_qd01");
        String body = JSONUtil.toJsonStr(param);
        String DS = DigestUtil.md5Hex("salt=" + n + "&t=" + t + "&r=" + r + "&b=" + body + "&q=");
        System.out.println(String.format("%s,%s,%s", t, r, DS));
    }
}
